package com.example.coolweatherreview.activity;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.coolweatherreview.R;
import com.example.coolweatherreview.net.NetworkAvailableUtils;
import com.example.coolweatherreview.service.AutoUpdateService;
import com.example.coolweatherreview.util.HttpCallbackListener;
import com.example.coolweatherreview.util.HttpUtil;
import com.example.coolweatherreview.util.Utility;

public class WeatherActivity extends Activity implements OnClickListener{
	
	private static final int CURRENT = 0;
	private static final int NEXT1 = 1;
	private static final int NEXT2 = 2;
	private static final int NEXT3 = 3;
	private static final int NEXT4 = 4;
	
	private Button backBtn;
	private Button refreshBtn;
	private TextView cityName;
	private TextView publishTime;
	private TextView currentTemp;
	private TextView wind;
	private TextView desp;
	private TextView notifition;
	private TextView tip;
	private TextView next1_Temp1;
	private TextView next1_Temp2;
	private TextView next2_Temp1;
	private TextView next2_Temp2;
	private TextView next3_Temp1;
	private TextView next3_Temp2;
	private TextView next4_Temp1;
	private TextView next4_Temp2;
	private ImageView weatherPic;
	private ImageView next1Pic;
	private ImageView next2Pic;
	private ImageView next3Pic;
	private ImageView next4Pic;
	
	public Handler handler = new Handler(){
		public void handleMessage(Message meg){
			Bitmap bitmap = (Bitmap) meg.obj;
			switch(meg.arg1){
			case CURRENT:
				weatherPic.setImageBitmap(bitmap);
				break;
			case NEXT1:
				next1Pic.setImageBitmap(bitmap);
				break;
			case NEXT2:
				next2Pic.setImageBitmap(bitmap);
				break;
			case NEXT3:
				next3Pic.setImageBitmap(bitmap);
				break;
			case NEXT4:
				next4Pic.setImageBitmap(bitmap);
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.weather_layout);
//		setImmerseLayout();
		initView();
	}
	
	/**
	 * 设置标题栏沉浸式
	 */
	private void setImmerseLayout() {
		if(Build.VERSION.SDK_INT>Build.VERSION_CODES.KITKAT){
//			Window window = getWindow();
//			window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			
	        //透明状态栏
	        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
	        //透明导航栏
	        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}

	}


	/**
	 * 初始化组件
	 */
	private void initView() {
		backBtn = (Button) findViewById(R.id.back_btn);
		refreshBtn = (Button) findViewById(R.id.refresh_btn);
		cityName = (TextView) findViewById(R.id.city_name);
		publishTime = (TextView) findViewById(R.id.publish_time);
		currentTemp = (TextView) findViewById(R.id.weather_temperature);		
		wind  = (TextView) findViewById(R.id.weather_wind);
		desp = (TextView) findViewById(R.id.weather_desp);
		notifition = (TextView) findViewById(R.id.weather_notice);
		tip =  (TextView) findViewById(R.id.tip);
		next1_Temp1 = (TextView) findViewById(R.id.next1_temp1);
		next1_Temp2 = (TextView) findViewById(R.id.next1_temp2);
		next2_Temp1 = (TextView) findViewById(R.id.next2_temp1);
		next2_Temp2 = (TextView) findViewById(R.id.next2_temp2);
		next3_Temp1 = (TextView) findViewById(R.id.next3_temp1);
		next3_Temp2 = (TextView) findViewById(R.id.next3_temp2);
		next4_Temp1 = (TextView) findViewById(R.id.next4_temp1);
		next4_Temp2 = (TextView) findViewById(R.id.next4_temp2);
		
		weatherPic = (ImageView) findViewById(R.id.weather_pic);
		next1Pic = (ImageView) findViewById(R.id.next1_pic);
		next2Pic = (ImageView) findViewById(R.id.next2_pic);
		next3Pic = (ImageView) findViewById(R.id.next3_pic);
		next4Pic = (ImageView) findViewById(R.id.next4_pic);
		
		backBtn.setOnClickListener(this);
		refreshBtn.setOnClickListener(this);
		
		String countyName = getIntent().getStringExtra("county_name");
		if (!TextUtils.isEmpty(countyName)) {
			// 有县级代号时就去查询天气
			tip.setVisibility(View.VISIBLE);
			tip.setText("同步中...");
			queryWeatherCode(countyName);
		} else {
			// 没有县级代号时就直接显示本地天气
			showWeather();
		}		
		
	}
	
	/**
	 * 查询县级代号所对应的天气代号
	 * @param countyName
	 */
	private void queryWeatherCode(String countyName) {
		final String API = "https://free-api.heweather.com/v5/";
		final String KEY = "df60be951e0e4b8aa09e3b3ccd00c5b2";
		String address = API +"weather?city="+convertCode(countyName)+"&key=" + KEY;		
		queryFromServer(address,"countyName");
	}
	
	/**
	 * 转码*/
	private static  String convertCode(String str){
		try {
			String convert = URLEncoder.encode(str,"utf-8");
			return convert;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询天气代号所对应的天气。
	 */
	private void queryWeatherInfo(String weatherCode) {
		String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html";
		queryFromServer(address, "weatherCode");
	}
	
	/**
	 * 根据传入的地址和类型去服务器查询天气代号或者天气信息
	 * @param address
	 * @param string
	 */
	private void queryFromServer(final String address, final String type) {
		if(NetworkAvailableUtils.is3rd(this)&&!NetworkAvailableUtils.isWifi(this)){
			Toast.makeText(this, "正在使用3G网络 注意流量啊！！！", Toast.LENGTH_SHORT).show();
		}		
		HttpUtil.setHttpRequest(address, new HttpCallbackListener() {
			
			@Override
			public void onFinish(String response) {
				if("countyName".equals(type)){
					Utility.handleWeatherResponse(WeatherActivity.this, response);
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							showWeather();
						}
						
					});
				}
			}
			
			@Override
			public void onError(Exception e) {
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						tip.setText("同步失败");
					}
				});
			}
		});
	}
	
	
	/**
	 * 从SharedPreferences文件中读取存储的天气信息，并显示到界面上。
	 */
	private void showWeather() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);		
		cityName.setText(prefs.getString("city_name", ""));
		publishTime.setText(prefs.getString("current_date", ""));
		currentTemp.setText(prefs.getString("current_temp", ""));
		wind.setText(prefs.getString("wind", ""));
		desp.setText(prefs.getString("weather_desc", ""));
		notifition.setText(prefs.getString("notification", ""));
		next1_Temp1.setText(prefs.getString("next1Temp1", ""));
		next1_Temp2.setText(prefs.getString("next1Temp2", ""));
		next2_Temp1.setText(prefs.getString("next2Temp1", ""));
		next2_Temp2.setText(prefs.getString("next2Temp2", ""));
		next3_Temp1.setText(prefs.getString("next3Temp1", ""));
		next3_Temp2.setText(prefs.getString("next3Temp2", ""));
		next4_Temp1.setText(prefs.getString("next4Temp1", ""));
		next4_Temp2.setText(prefs.getString("next4Temp2", ""));
		
		loadPic(prefs.getString("currentPicUrl", ""),CURRENT);
		loadPic(prefs.getString("next1Pic", ""),NEXT1);
		loadPic(prefs.getString("next2Pic", ""),NEXT2);
		loadPic(prefs.getString("next3Pic", ""),NEXT3);
		loadPic(prefs.getString("next4Pic", ""),NEXT4);
		
		tip.setVisibility(View.GONE);
		Intent intent = new Intent(this, AutoUpdateService.class);
		startService(intent);
	}
	
	/**
	 * 加载天气图片
	 * @param url
	 */
	private void loadPic(final String code,final int type){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String url = "http://files.heweather.com/cond_icon/" + code +".png";				URL myPicUrl;
				Bitmap bitmap = null;
				try{
					myPicUrl = new URL(url);
					//获得连接
					HttpURLConnection conn = (HttpURLConnection) myPicUrl.openConnection();
					//设置超时时间
					conn.setConnectTimeout(8000);
					//连接设置获得数据流
					conn.setDoInput(true);
					//不使用缓存
					conn.setUseCaches(false);
					//得到数据了
					InputStream is = conn.getInputStream();
					//解析得到图片
					bitmap = BitmapFactory.decodeStream(is);
					//关闭数据流
					is.close();
					Message meg = new Message();
					meg.arg1 = type;
					meg.obj = bitmap;
					handler.sendMessage(meg);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	
	
	/**
	 * 按钮点击事件
	 */
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back_btn:
			Intent intent = new Intent(this,ChooseActivity.class);
			intent.putExtra("from_weather_activity", true);
			startActivity(intent);
			finish();
			break;
		case R.id.refresh_btn:
			tip.setText("同步中...");
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			String countyCode = prefs.getString("city_name", "");
			if(!TextUtils.isEmpty(countyCode)){
				queryWeatherCode(countyCode);
			}
			break;
		default:
			break;
		}
	}	
}

